<template>
  <div class="search-box">
    <form class="search"
          action="/">
      <van-search v-model="searchTxt"
                  show-action
                  placeholder="请输入搜索关键词"
                  @search="onSearch"
                  @cancel="onCancel"
                  @focus="isShowReults = false" />
    </form>
    <SearchResults :searchtext="searchTxt"
                   v-if="isShowReults" />
    <SearchHistory @search="onSearch"
                   :historys="historys"
                   v-else-if="!searchTxt" />
    <SearchSuggestion @search="onSearch"
                      :searchtext="searchTxt"
                      v-else />

  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory'
import SearchResults from './components/SearchResults'
import SearchSuggestion from './components/SearchSuggestion'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'search',
  data () {
    return {
      searchTxt: '',
      isShowReults: false,
      historys: getItem('HISTORY') || []
    }
  },
  components: {
    SearchHistory,
    SearchResults,
    SearchSuggestion
  },
  watch: {
    historys () {
      setItem('HISTORY', this.historys)
    }
  },
  created () {

  },

  methods: {
    onSearch (val) {
      if (val.trim().length === 0) return
      const index = this.historys.indexOf(val)
      if (index !== -1) {
        this.historys.splice(index, 1)
      }
      this.historys.unshift(val)
      this.searchTxt = val
      this.isShowReults = true
    },
    onCancel () {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped lang='less'>
.search-box {
  .van-search {
    background-color: #3296fa;
    .van-search__action {
      color: #fff;
    }
  }
  .search {
    position: sticky;
    top: 0;
    z-index: 2;
  }
}
</style>
